<?php
class Information extends Admin_Controller
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('information_model','information');
	}
	
	function index()
	{
		if(!empty($_GET['search']))
		{
			$this->information->where('title like \'%'.$_GET['search'].'%\'');
		}
		$data['result'] = $this->information->order('desc')->get();
		$data['paginaion'] = $this->information->pagination();
		$this->template->build('information_index',$data);
	}
	
	function form($id = NULL)
	{
		$data['rs'] = $this->information->get_row($id);
		$this->template->append_metadata(js_validate());
		$this->template->build('information_form',$data);
	}
	
	function index2()
	{
		if(!empty($_GET['search']))
		{
			$this->information->where('title like \'%'.$_GET['search'].'%\'');
		}
		$data['result'] = $this->information->order('desc')->get();
		$data['paginaion'] = $this->information->pagination();
		$this->template->build('information_index2',$data);
	}
	
	function save()
	{
		if($_POST)
		{$this->db->debug = true;
			if(empty($_POST['id']))
			{
				add_log('เพิ่มข่าวประชาสัมพันธ์หัวข้อ "'.$_POST['title'].'"');
			}
			else
			{
				add_log('แก้ไขข่าวประชาสัมพันธ์หัวข้อ "'.$_POST['title'].'"');
			}
			
			$_POST['user_id'] = $this->session->userdata('id');
			$id = $this->information->save($_POST);
			$this->load->model('files/file_model');
			$this->load->model('files/file_item_model');
			$file_id = $this->db->getone('SELECT ID FROM FILES WHERE FILES.FUND_ID = ?', array($id));
			if(empty($file_id))
			{
				$data = array(
					'fund_id' => $id,
					'name' => 'information' 
				);
				$file_id = $this->file_model->save($data);
			}
			$data = NULL;
			foreach($_FILES['src']['name'] as $key => $filename)
			{
				if(!empty($filename))
				{
					$ext = pathinfo($filename, PATHINFO_EXTENSION);
					$new_filename = time().$key.'.'.$ext;
					if(copy($_FILES['src']['tmp_name'][$key], 'uploads/doc/'.$new_filename))
					{
						$data = array(
							'file_id' => $file_id,
							'filename' => $_POST['filename'][$key]
						);
						$data['src'] = $new_filename;
						$this->file_item_model->save($data);
					}
				}
			}
			set_notify('success', lang('save_data_complete'));
		}
		redirect('information');
	}
	
	function delete($id)
	{
		$rs = $this->information->get_row($id);
		add_log('ลบข่าวประชาสัมพันธ์หัวข้อ "'.$rs['title'].'"');
		$this->information->delete($id);
		set_notify('success', lang('delete_data_complete'));
		redirect($_SERVER['HTTP_REFERER']);
	}
	
}
?>